#include "stdafx.h"
#include "net/MultipartWriter.hpp"
#include "net/MessageHeader.hpp"
#include "math/random.hpp"
using JHCPP::math::CRandom;
#include "utils/numberformatter.hpp"
using JHCPP::utils::CNumberFormatter;

NET_NAMESPACE_BEGIN

CMultipartWriter::CMultipartWriter(std::ostream& ostr)
	: m_ostr(ostr),
	m_boundary(createBoundary()),
	m_firstPart(true)
{
}

CMultipartWriter::CMultipartWriter(std::ostream& ostr, const std::string& boundary)
	: m_ostr(ostr),
	m_boundary(boundary),
	m_firstPart(true)
{
	if (m_boundary.empty())
		m_boundary = createBoundary();
}

CMultipartWriter::~CMultipartWriter()
{
}

void CMultipartWriter::nextPart(const CMessageHeader& header)
{
	if (m_firstPart)
		m_firstPart = false;
	else
		m_ostr << "\r\n";
	m_ostr << "--" << m_boundary << "\r\n";
	header.write(m_ostr);
	m_ostr << "\r\n";
}

void CMultipartWriter::close()
{
	m_ostr << "\r\n--" << m_boundary << "--\r\n";
}

const std::string& CMultipartWriter::boundary() const
{
	return m_boundary;
}

std::string CMultipartWriter::createBoundary()
{
	std::string boundary("MIME_boundary_");
	CRandom rnd;
	CNumberFormatter::appendHex(boundary, rnd.next(), 8);
	CNumberFormatter::appendHex(boundary, rnd.next(), 8);
	return boundary;
}

std::ostream& CMultipartWriter::stream()
{
	return m_ostr;
}

NET_NAMESPACE_END
